<template>
    <a-tree-select v-model:value="value" tree-data-simple-mode style="width: 100%"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="treeData" placeholder="Please select"
        :load-data="onLoadData" autoExpandParent/>
</template>
<script lang="ts" setup>
import { DefaultOptionType } from 'ant-design-vue/lib/vc-tree-select/TreeSelect';
import type { TreeSelectProps } from 'ant-design-vue';
import { PropType, VNode, onMounted, ref, watch } from 'vue';
import { requestData } from '..';
import request from '/@/utils/request'
 const value = ref<string>();
// const pId = ref<number>();
const treeData = ref<TreeSelectProps['treeData']>([]);
const mTreeData = ref<any>([])
const props = defineProps({
    searchPlaceholder: {
        type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
    },
    suffixIcon: {
        type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
    },
    tagRender: {
        type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
    },
    title: {
        type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
    },
    notFoundContent: {
        type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
    },
    ptreeData: {
        type: [Array] as PropType<DefaultOptionType[]>
    },
    api: { // 接口地址或接口函数--->新增属性
        type: [Function, String] as PropType<((param: any) => Promise<any>) | String>
    },
    params: {
        type: Object,
        default() {
            return {}
        }
    },
    immediate: { // 是否立即加载数据
        type: Boolean,
        default: true
    },
    valueField: { // 值字段
        type: String,
        default: 'value'
    },
    labelField: { // 显示字段
        type: String,
        default: 'label'
    },
    childrenField: { // 子节点字段
        type: String,
        default: 'children'
    },
})
// watch(
//     () => {
//         console.log('77888999-----', value.value);
//     },
//     () => {
//         console.log('ghjhjty-----', pId.value);
//     }
// );
onMounted(() => {
    if (props.immediate) {
        console.log('props.api', props.api);
        console.log('props.params', props.params);
        // console.log('props.params',props);
        requestData(props.api, props.params).then((res) => {
            // console.log('mTreeData----',res.content);

            const v = res.content || res
            let mData: any = []
            let param: any = {}
            if (v instanceof Array) {
                console.log('mTreeData----', res);
                v.forEach((item: any, index: any) => {
                    // param.OrgID = item.id
                    //    let mArray = reload(param)
                    // console.log('vvvvv----',param);
                    // console.log('vvvvv----',mArray);

                    mData.push(genTreeNode(item.id, props.params.OrgID, false, item.name),)
                    treeData.value?.push(genTreeNode(item.id, props.params.OrgID, false, item.name),)
                })


                // genTreeNode(v.id, false,v.name),
                // treeData.value.push(v)
                // treeData.value = [...mData]
                console.log('mTreeData.value', mData);
            }
        })

        console.log('mTreeData.value-----', treeData.value);

    }
})
// const genTreeNode = (parentId: number, isLeaf = false, name: string): TreeSelectProps['treeData'][number] => {
//     const random = Math.random().toString(36).substring(2, 6);
//     return {
//         id: random,
//         pId: parentId,
//         value: 'random',
//         title: isLeaf ? 'Tree Node' : name,
//         isLeaf,
//     };
// };
const genTreeNode = (id: number, parentId: number, isLeaf = false, name: string): TreeSelectProps['treeData'][number] => {
    // const random = Math.random().toString(36).substring(2, 6);
    if(props.api === '/Roles/GetRoleList') isLeaf = true

    return {
        id: id,
        pId: parentId,
        value: id,
        title: isLeaf ? name : name,
        isLeaf,
    };
};
// const monLoadData = (treeNode: TreeSelectProps['treeData'][number]) => {
//    const _this = this;
//    return new Promise((resolve) => {
//      if (Array.isArray(treeNode.dataRef.children) && treeNode.dataRef.children.length) {
//        console.log('treeNode.dataRef.children', treeNode.dataRef.children);
//        resolve()
//        return
//      }
//      //如果没有值，根据当前节点id获取子节点并挂在树节点中，添加到对应父节点的children中
//      publicapi.constructionQueryOrg(treeNode.dataRef.id).then((res) => {
//          treeNode.dataRef.children = res;
//          _this.orgTree = [..._this.orgTree];
//          console.log('treeNode.dataRef.children', treeNode.dataRef.children);
//      }).catch();
//      resolve()
//    })
//  }
const onLoadData = (treeNode: TreeSelectProps['treeData'][number]) => {
    // const onLoadData = () => {
    // console.log('3434sdss---');

    // return new Promise(resolve => {
    const { id } = treeNode.dataRef;
    props.params.OrgID = id
    console.log('3434sdss---', props.params); 
    let apiFun: ((param: any)=>Promise<any>) | undefined
    return new Promise((resolve, reject) => {
     if (Array.isArray(treeNode.dataRef.children) && treeNode.dataRef.children.length) {
       console.log('treeNode.dataRef.children', treeNode.dataRef.children);
       resolve({})
       return
     }
     apiFun = (param: any) => request.post(props.api as any, param)
     if(apiFun) {
      apiFun({
        ...props.params
      }).then((res: any)=>{
        resolve(res)
        console.log('wertewrewrxdf',res);
        const v = res.content || res
        if (v instanceof Array) {
            mTreeData.value = v
            let mData:any = []
            mTreeData.value.forEach((item: any) => {
                mData.push(genTreeNode(item.id, id, false, item.name),)
            });
            treeData.value = treeData.value?.concat(mData)
            console.log('hhhhhh----',mData);
            console.log('mmmmm----', treeData.value);

        }

      }).catch(reject)
    } else {
      resolve({})
    }
    })
    // reload(props.params)

    // requestData(props.api, {
    //     ...props.params,

    // }).then(res => {
    //     const v = res.content || res
    //     if (v instanceof Array) {
    //         mTreeData.value = v

    //         // mTreeData.value.forEach((item: any) => {
    //         //     treeData.value?.push(genTreeNode(item.id, id, false, item.name),)
    //         // });
    //         // console.log('hhhhhh----',v);
    //         console.log('hhhhhh----', mTreeData.value);

    //     }
    // })



    //   setTimeout(() => {
    //     treeData.value = treeData.value.concat([ 
    //       genTreeNode(id, false),
    //       genTreeNode(id, true),
    //       genTreeNode(id, true),
    //     ]);
    //     console.log(treeData.value);
    //     resolve(true);
    //   }, 300);
    // });
};
// const reload = (params: any) => {
//     requestData(props.api, {
//         ...props.params,
//         ...params
//     }).then(res => {
//         const v = res.content || res
//         if (v instanceof Array) {
//             mTreeData.value = v
//             // console.log('hhhhhh----',v);
//             console.log('hhhhhh----', mTreeData.value);

//         }
//     })
// }
defineExpose({
    reload(params: any) {
        requestData(props.api, {
            // ...props.params,
            ...params
        }).then(res => {
            const v = res.content || res
            if (v instanceof Array) {
                treeData.value = v
            }
        })
    }
})
</script>